package com.blogSystem.article.interceptor;

import com.blogSystem.article.dao.ArticleDao;
import com.blogSystem.article.service.ArticleService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.web.servlet.HandlerInterceptor;
import util.JwtUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {


    @Autowired
    private  HttpServletRequest request;

    @Autowired
    private ArticleService articleService;
    @Autowired
    private ArticleDao articleDao;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        JwtUtil jwtUtil=new JwtUtil();
        System.out.println("验证+++++++++++++++++++++++++++++++");
        String header=request.getHeader("Authorization");
        if(header!=null||!"".equals(header)){
            if(header.startsWith("Bearer")){
                String token=header.substring(7);
                System.out.println(token);
                //解析
                try{
                    Claims claims=jwtUtil.parseJWT(token);
                    String roles= (String) claims.get("roles");

                    if(roles!=null||"ROLE_SUPER".equals(roles)){
                        request.setAttribute("claims_super",token);
                    }
                    if(roles!=null||"ROLE_ADMIN".equals(roles)){
                        request.setAttribute("claims_admin",token);
                    }
                    if(roles!=null||"ROLE_USER".equals(roles)){
                        request.setAttribute("claims_user",token);
                    }
                }catch (Exception e){
                    throw new RuntimeException("令牌有误！");
                }
            }
        }
        return true;

    }
}
